﻿using UnityEngine;
using System.Collections;
using System.Threading;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System;
using System.IO;
using System.Text;
namespace com.lib.net
{
    /// <summary>
    /// 网络基类
    /// </summary>
    public class NetWorks
    {
        /// <summary>
        /// 回调事件
        /// </summary>
        /// <param name="o"></param>
        public delegate void NetCall(object o);

        private static NetWorks instance = null;

        public static NetWorks Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new NetWorks();
                }

                return instance;
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        public void Send(NetType type, object data)
        {
            switch (type)
            {
                case NetType.HTTP:
                    if (HttpNetWork.Instance == null)
                    {
                        Logger.LogError("The Scripts HttpNetWork Should AddComponent On GameObject Break");
                        return;
                    }
                    HttpNetWork.Instance.Send(data);

                    break;

                case NetType.TCP:
                    if (TcpNetWork.Instance == null)
                    {
                        Logger.LogError("The Scripts TcpNetWork Should AddComponent On GameObject Break");
                        return;
                    }
                    TcpNetWork.Instance.Send(data);
                    break;

                case NetType.UDP:


                    break;
            }

        }


        public void getHttpData(string url,NetCall call)
        {
            HttpNetWork.Instance.getHttpData(url, call);

        }

        public void getHttpTexture(string url, NetCall call)
        {
            HttpNetWork.Instance.getHttpTexture(url, call);

        }



        public void Init(NetType type, NetCall call, string url = "", int port = 0)
        {
            if (call == null)
            {
                Logger.LogError("The CallBack Is Null Please Check");
                return;
            }
            switch (type)
            {
                case NetType.HTTP:
                    if (HttpNetWork.Instance == null)
                    {
                        Logger.LogError("The Scripts HttpNetWork Should AddComponent On GameObject Break");
                        return;
                    }
                    HttpNetWork.Instance.Init(url, call);


                    break;

                case NetType.TCP:

                    
                    if (TcpNetWork.Instance == null)
                    {
                        Logger.LogError("The Scripts TcpNetWork Should AddComponent On GameObject Break");
                        return;
                    }
                    TcpNetWork.Instance.Init(url,port,call);

                    break;
            }

        }

        /// <summary>
        /// Res 解密
        /// </summary>
        /// <param name="array"></param>
        public string ResDecode(byte[] array)
        {
            return System.Text.Encoding.UTF8.GetString(array).Decode();
        }
        /// <summary>
        /// Res加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public object ResEncode(object data)
        {
            return data;
        }

        /// <summary>
        ///启动线程加载,仅仅用来下载文本流
        /// </summary>
        public void getHttpDataByThread(string url, NetCall call)
        {
            Hashtable hash = new Hashtable();
            hash["url"] = url;
            hash["call"] = call;
            ParameterizedThreadStart p = new ParameterizedThreadStart(StartHttpThread);
            Thread t = new Thread(p);
            t.Start(hash);
        }


        private void StartHttpThread(object o)
        {
            Hashtable hash = o as Hashtable;
            string url = hash["url"].ToString();
            NetCall call = (NetCall)hash["call"];
            HttpWebResponse data = CreateGetHttpResponse(url);
            if (data == null)
            {
                call(null);
                return;
            }
            using (Stream s = data.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                call(reader.ReadToEnd());
            }
        }

        public  HttpWebResponse CreateGetHttpResponse(string url)
        {
            try
            {
                HttpWebRequest request = null;
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    //对服务端证书进行有效性校验（非第三方权威机构颁发的证书，如自己生成的，不进行验证，这里返回true）
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;    //http版本，默认是1.1,这里设置为1.0
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "GET";

                //设置代理UserAgent和超时
                //request.UserAgent = userAgent;
                //request.Timeout = timeout;
                return request.GetResponse() as HttpWebResponse;

            }
            catch (Exception)
            {

                return null;
            }
        }

        /// <summary>
        /// 验证证书
        /// </summary>
        private  bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors == SslPolicyErrors.None)
                return true;
            return false;
        }  


    }

    /// <summary>
    /// 数据
    /// </summary>


    /// <summary>
    /// 数据存放
    /// </summary>
    public class NetData
    {
        public static bool HttpInit = false;

        public static bool TcpInit = false;

        public static bool UdpInit = false;

        public static bool CanSend = false;
    }


    /// <summary>
    /// 网络连接类型
    /// </summary>
    public enum NetType
    {
        HTTP,
        UDP,
        TCP

    }
}
public class NetCallData
{
    public int cmd { get; set; }

    public int state { get; set; }

    public Params value { get; set; }
}